"""用户信息模型"""

from sqlalchemy import INT, String
from sqlalchemy.orm import Mapped, mapped_column
from werkzeug.security import check_password_hash
from . import db


class UserModel(db.Model):
    """
    用户表
    """

    __tablename__ = "users"
    # 自增起始值
    __table_args__ = {"mysql_auto_increment": "10000"}

    # 主键id
    id: Mapped[int] = mapped_column(INT, primary_key=True, autoincrement=True)

    # 用户名
    user_name: Mapped[str] = mapped_column(
        String(36), unique=True, nullable=False
    )
    # 密码
    pwd_hash: Mapped[str] = mapped_column(String(200), nullable=False)
    # 头像
    avatar: Mapped[str] = mapped_column(String(200), default="")

    def create_user(self):
        """创建用户"""
        db.session.add(self)
        db.session.commit()

    def check_password(self, pwd):
        """
        验证密码
        :param pwd 密码
        :return: 布尔值
        """
        return check_password_hash(self.pwd_hash, pwd)

    @classmethod
    def find_by_username(cls, username):
        """
        根据用户名查找用户
        :param username 用户名
        :return: 模型实例
        """
        return db.session.execute(
            db.select(cls).filter_by(user_name=username)
        ).first()
